package com.twotiger.and;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import cn.jpush.android.api.JPushInterface;

import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.controller.EaseUI;
import com.twotiger.and.bean.BanklistItem;
import com.twotiger.and.bean.CashBank;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.ProjectdetailData;
import com.twotiger.and.bean.User;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.service.OtherService;
import com.twotiger.and.service.UserService;
import com.twotiger.and.util.CrashHandler;
import com.umeng.analytics.MobclickAgent;

@SuppressLint("NewApi")
public class TwoTigerApp extends Application {
    // 退出应用程序,销毁Activity相关
    private static List<Activity> activitys = null;
    private static TwoTigerApp instance;
    private String Dayinverst_timestamp;
    private String DealRecord_timestamp;
    private String Repayment_timestamp;
    private String AssetRecord_timestamp;
    private String couponlist_timestamp;
    private String projectlist_timestamp;
    private String systemmessage_timestamp;
    private String inverstcouponjson;
    private ProjectdetailData projectdetaildate;

    /**user*/
    private User user;
    private UserAsset userAsset;
    private List<BanklistItem> userBanks = new ArrayList<BanklistItem>();
    private List<BanklistItem> avaliableBanks = new ArrayList<BanklistItem>();
    private BanklistItem quickBank;
    private List<CashBank> cashBankList = new ArrayList<CashBank>();
    private CashBank llCashBank;

    /**service*/
    public OtherService otherService;
    public UserService userService;

    /**手势密码校验状态*/
    public boolean vaildGesturePwd;

    private boolean isRegistSuccess;//注册是否成功的标志

    private boolean isNeed; //控制检查token过期的请求只有一次

    private boolean isNeedReload; //web页面是否需要重新加载
    
    private int witchTag;  //进入paojectpage列表页之后是显示直投列表还是转让列表
    
    
    public int getWitchTag() {
        return witchTag;
    }

    public void setWitchTag(int witchTag) {
        this.witchTag = witchTag;
    }

    private Map<String, ConstantDataUnit> constantDataMap; // 已key为键保存起来的常量数据集合


    public Map<String, ConstantDataUnit> getConstantDataMap() {
        return constantDataMap;
    }

    public void setConstantDataMap(Map<String, ConstantDataUnit> constantDataMap) {
        this.constantDataMap = constantDataMap;
    }

    public boolean isNeedReload() {
        return isNeedReload;
    }

    public void setNeedReload(boolean isNeedReload) {
        this.isNeedReload = isNeedReload;
    }

    public boolean isNeed() {
        return isNeed;
    }

    public void setNeed(boolean isNeed) {
        this.isNeed = isNeed;
    }

    public boolean isRegistSuccess() {
        return isRegistSuccess;
    }

    public void setRegistSuccess(boolean isRegistSuccess) {
        this.isRegistSuccess = isRegistSuccess;
    }

    public void setCashBanks(List<CashBank> cashBanks) {
        this.cashBankList = cashBanks;
        llCashBank = null;
        for (CashBank item : cashBanks) {
            if ("false".equals(item.isView)) {
                llCashBank = item; //连连卡
            }
        }
    }

    public List<CashBank> getcashBanks() {
        return cashBankList;
    }

    public CashBank getLLCashBank() {
        return llCashBank;
    }

    public void setUserBanks(List<BanklistItem> userBanks) {
        this.userBanks = userBanks;
        this.avaliableBanks = new ArrayList<BanklistItem>();
        for (BanklistItem item : userBanks) {
            if (item.isQuick) {
                quickBank = item;
            }
            if (item.isValid) {
                avaliableBanks.add(item);
            }
        }
    }

    public List<BanklistItem> getAvaliableBanks() {
        return avaliableBanks;
    }

    public List<BanklistItem> getUserBanks() {
        return userBanks;
    }

    public BanklistItem getQuickBank() {
        return quickBank;
    }

    public void setUserAsset(UserAsset userAsset) {
        this.userAsset = userAsset;
    }

    public UserAsset getUserAsset() {
        if (userAsset == null) {
            userAsset = new UserAsset();
        }
        return userAsset;
    }

    public ProjectdetailData getProjectdetaildate() {
        return projectdetaildate;
    }

    public void setProjectdetaildate(ProjectdetailData projectdetaildate) {
        this.projectdetaildate = projectdetaildate;
    }

    public String getInverstcouponjson() {
        return inverstcouponjson;
    }

    public void setInverstcouponjson(String inverstcouponjson) {
        this.inverstcouponjson = inverstcouponjson;
    }

    public String getSystemmessage_timestamp() {
        return systemmessage_timestamp;
    }

    public void setSystemmessage_timestamp(String systemmessage_timestamp) {
        this.systemmessage_timestamp = systemmessage_timestamp;
    }

    public String getProjectlist_timestamp() {
        return projectlist_timestamp;
    }

    public void setProjectlist_timestamp(String projectlist_timestamp) {
        this.projectlist_timestamp = projectlist_timestamp;
    }

    public String getCouponlist_timestamp() {
        return couponlist_timestamp;
    }

    public void setCouponlist_timestamp(String couponlist_timestamp) {
        this.couponlist_timestamp = couponlist_timestamp;
    }

    public String getAssetRecord_timestamp() {
        return AssetRecord_timestamp;
    }

    public void setAssetRecord_timestamp(String assetRecord_timestamp) {
        AssetRecord_timestamp = assetRecord_timestamp;
    }

    public String getRepayment_timestamp() {
        return Repayment_timestamp;
    }

    public void setRepayment_timestamp(String repayment_timestamp) {
        Repayment_timestamp = repayment_timestamp;
    }

    public String getDayinverst_timestamp() {
        return Dayinverst_timestamp;
    }

    public void setDayinverst_timestamp(String dayinverst_timestamp) {
        Dayinverst_timestamp = dayinverst_timestamp;
    }

    public String getDealRecord_timestamp() {
        return DealRecord_timestamp;
    }

    public void setDealRecord_timestamp(String dealRecord_timestamp) {
        DealRecord_timestamp = dealRecord_timestamp;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        if (this.user != null) {//深度复制
            extend(user, this.user);
        } else {
            this.user = user;
        }
        if (user.gesturePwd == null) {
            user.gesturePwd = userService.getUser().gesturePwd;
        }
        if (user.gesturePwd != null) {
            userService.saveUser(user);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(this);
        instance = this;
        activitys = new LinkedList<Activity>();
        initJPush();
        initUmeng();
        initServices();
        initUserInfo();
        initEaseUI();
    }

    private void initEaseUI() {
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        EaseUI.getInstance().init(this, options);
    }

    private void initUmeng() {
        MobclickAgent.setDebugMode(true); //集成测试服务
        MobclickAgent.openActivityDurationTrack(false);//禁止默认的页面统计方式,包含fragment的应用中需要调用此方法
    }

    private void initJPush() {
        JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this); // 初始化 JPush
    }

    public TwoTigerApp() {
        activitys = new LinkedList<Activity>();
    }

    // 单例模式中获取唯一的MyApplication实例
    public static TwoTigerApp getInstance() {
        if (null == instance) {
            instance = new TwoTigerApp();
        }
        return instance;
    }

    /**
     * has more activities
     * @return
     */
    public boolean hasMoreActivities() {
        return activitys.size() > 1;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activitys != null && activitys.size() > 0) {
            if (!activitys.contains(activity)) {
                activitys.add(activity);
            }
        } else {
            activitys.add(activity);
        }
    }

    public void removeActivity(Activity activity) {
        if (activitys != null) {
            if (activitys.contains(activity)) {
                activitys.remove(activity);
            }
        }
    }

    public void clearcache() {
        activitys.remove(0);
        if (activitys != null && activitys.size() > 0) {
            for (Activity activity : activitys) {
                if (activity != null) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * Activity的容器必须用appliction作为上下文，才能保证唯一性
     */
    public void exit() {
        if (activitys != null && activitys.size() > 0) {
            for (Activity activity : activitys) {
                if (activity != null) {
                    activity.finish();
                }
            }
        }
        //集成环信客服之后，再双击退出应用。此时调用System.exit(0)方法会造成toast卡在屏幕上很长时间。故避免调用此方法退出应用！    time: 2016.05.03
        //咨询客服之后说是删掉manifest中注册的环信service和receiver就可以调用System.exit(0)了。    time: 2016.05.11
        System.exit(0);
    }

    public void initServices() {
        otherService = new OtherService(getApplicationContext());
        userService = new UserService(getApplicationContext());
    }

    private void initUserInfo() {
        setUser(userService.getUser());
    }

    public void closeGesture() {
        setGesturePwd(null);
    }

    public void logout() {
        //退出、清理所有用户信息
        User tmp = new User();
        tmp.phone = this.user.phone;
        userService.saveUser(tmp);
        this.user = tmp;
        setUserAsset(new UserAsset());
        setUserBanks(new ArrayList<BanklistItem>());
        quickBank = null;
        clearWebViewCache();
    }

    /**
     * 彻底清除缓存（banner 登陆信息清除）  清除webview中的登陆信息
     */
    public void clearWebViewCache() {
        // 清除cookie即可彻底清除缓存
        CookieSyncManager.createInstance(getApplicationContext());
        CookieManager.getInstance().removeAllCookie();
    }

    public void setGesturePwd(String gesturePwd) {
        this.user.gesturePwd = gesturePwd;
        this.vaildGesturePwd = true;
        //关闭手势密码、仅保留手机
        if (user.gesturePwd == null) {
            User u = new User();
            u.phone = this.user.phone;
            userService.saveUser(u);
            otherService.closeGesture();
        } else {
            otherService.openGesture();
            userService.saveUser(user);
        }
    }

    private void extend(User from, User to) {
        try {
            Field[] fields = User.class.getFields();
            for (int i = 0; i < fields.length; i++) {
                Object v = fields[i].get(from);
                if (v != null) {
                    fields[i].set(to, v);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}